package com.kaiwukj.android.ufamily.mvp.ui.page.service.repairs;

import android.app.Activity;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.mvp.browse.JBrowseImgActivity;
import com.kaiwukj.android.ufamily.mvp.browse.JPhotosInfos;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.RepairsResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.ComplainType;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.UploadAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.PopupWindowUtil;
import com.kaiwukj.android.ufamily.utils.AudioUtils;
import com.kaiwukj.android.ufamily.utils.FormatUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.kaiwukj.android.ufamily.mvp.ui.adapter.UploadAdapter.SHOWTYPE;
import static com.kaiwukj.android.ufamily.utils.Utils.runOnUiThread;

/**
 * @author Charles
 * @date 2019/8/16.
 * description：Kaiwu
 */
public class RepairsListAdapter extends BaseQuickAdapter<RepairsResult, BaseViewHolder> {
    private Activity activity;
    private UploadAdapter uploadAdapter;
    private MediaPlayer mediaPlayer;
    private Timer recordTimer;
    private OnFinishListener onFinishListener;

    public void confirmFinish(int position) {
        getData().get(position).setStatus(4);
        notifyItemChanged(position);
    }

    public RepairsListAdapter() {
        super(R.layout.item_repairs_record, new ArrayList<>());
        addChildClickViewIds(R.id.tv_confirm_finish);
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

    @Override
    protected void convert(BaseViewHolder helper, RepairsResult item) {
        TextView tvRepairsType = helper.getView(R.id.tv_repairs_type);
        TextView tvCommitTime = helper.getView(R.id.tv_commit_time);
        TextView tvStatus = helper.getView(R.id.tv_status);
        TextView tvApponitment = helper.getView(R.id.tv_appointment_time);
        TextView tvAppointTime = helper.getView(R.id.tv_appoint_time_flag);

//        维修人员信息
        LinearLayout llRepairmanInfo = helper.getView(R.id.ll_repairman_info);
        TextView tvRepairmanName = helper.getView(R.id.tv_repairman_name);
        TextView tvRepairmanPhone = helper.getView(R.id.tv_repairman_phone);

//        评价
        TextView tvEveluate = helper.getView(R.id.tv_eveluate);
        LinearLayout llEveluate = helper.getView(R.id.ll_eveluate);
        RecyclerView rvEveluateImgs = helper.getView(R.id.rv_eveluate_imgs);

//        确认完成
        TextView tvConfirmFinish = helper.getView(R.id.tv_confirm_finish);
        tvConfirmFinish.setVisibility(View.GONE);

        TextView tvContent = helper.getView(R.id.tv_content);
        TextView tvRecord = helper.getView(R.id.tv_record);
        RecyclerView rvUpload = helper.getView(R.id.rv_complain_upload);

        tvApponitment.setText(FormatUtils.formatTime(item.getBookingTime()));
        tvAppointTime.setText("预约时间: ");
//        维修状态：1：待处理 2：延迟处理 3：处理中 4:已处理
        if (item.getStatus() == 1) {
            llRepairmanInfo.setVisibility(View.GONE);
            tvStatus.setText("待处理");
        } else if (item.getStatus() == 2) {
            llRepairmanInfo.setVisibility(View.GONE);
            tvStatus.setText("延迟处理");
            tvApponitment.setText(FormatUtils.formatTime(item.getDelayProcessTime()));
            tvAppointTime.setText("延迟时间: ");
        } else if (item.getStatus() == 3) {
            tvConfirmFinish.setVisibility(View.VISIBLE);
            tvStatus.setText("处理中");
        } else if (item.getStatus() == 4) {
            tvStatus.setText("已处理");
        } else {
            tvStatus.setText("未知状态");
        }

//        报修类型：1房屋质量、2电梯、3楼梯、4公共设施、5健身器材、6公共照明、7其他
        List<ComplainType> data = new ArrayList<>();
        data.add(new ComplainType(1, "房屋质量"));
        data.add(new ComplainType(2, "电梯"));
        data.add(new ComplainType(3, "楼梯"));
        data.add(new ComplainType(4, "公共设施"));
        data.add(new ComplainType(5, "健身器材"));
        data.add(new ComplainType(6, "公共照明"));
        data.add(new ComplainType(7, "其他"));
        for (ComplainType complainType : data) {
            if (item.getType() == complainType.getId()) {
                tvRepairsType.setText(complainType.getTypeName());
                break;
            }
        }
        // tvApponitment.setText(item.getComplainTime());
        tvCommitTime.setText(String.format("提交时间:%s", FormatUtils.formatTime(item.getCreateTime())));
        tvRepairmanName.setText(item.getMasterName());
        tvRepairmanPhone.setText(item.getMasterPhone());
        tvRepairmanPhone.setOnClickListener(view -> {
            PopupWindowUtil.createCallDialog(activity, item.getMasterPhone()).showCenter(R.layout.activity_complain);
        });
//        判断是否有评价
        if (TextUtils.isEmpty(item.getFinishReply())) {
            llEveluate.setVisibility(View.GONE);
        } else {
            llEveluate.setVisibility(View.VISIBLE);
        }
        tvEveluate.setText(String.format("评价:%s", item.getFinishReply()));
        rvEveluateImgs.setLayoutManager(new GridLayoutManager(getContext(), 4));
        String str = item.getFinishImg();
        if (!TextUtils.isEmpty(str)) {
            List<String> urls = Arrays.asList(str.split(","));
            rvEveluateImgs.setAdapter(new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_img, urls) {
                @Override
                protected void convert(BaseViewHolder helper, String item) {
                    ImageView ivImg = helper.getView(R.id.iv_image);
                    Glide.with(getContext()).load(item).into(ivImg);
                    ivImg.setOnClickListener(v -> {
                        ArrayList<JPhotosInfos> infos = new ArrayList<>();
                        for (int i = 0; i < getData().size(); i++) {
                            Rect rect = new Rect();
                            rect.left = 32;
                            rect.bottom = 12;
                            rect.top = 12;
                            rect.right = 32;
                            JPhotosInfos photosInfos = new JPhotosInfos();
                            infos.add(photosInfos.build(rect));
                            infos.add(photosInfos);
                        }
                        JBrowseImgActivity.start(getContext(), new ArrayList<>(getData()), helper.getAdapterPosition(), infos, ivImg);

                    });
                }
            });
        }

        tvConfirmFinish.setOnClickListener(view -> onFinishListener.OnFinish(helper.getLayoutPosition()));

        tvContent.setText(item.getContent());
        // tvRecord.setVisibility(TextUtils.isEmpty(item.getVoice()) ? View.GONE : View.VISIBLE);
        Observable.create((ObservableOnSubscribe<Integer>) emitter ->
                emitter.onNext(AudioUtils.getNetAudioTime(item.getVoice())))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        tvRecord.setVisibility(View.VISIBLE);
                        tvRecord.setText(String.format("%s\"", integer));
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (e instanceof IOException) {
                            tvRecord.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
        tvRecord.getBackground().setLevel(2);
        recordTimer = new Timer();
        tvRecord.setOnClickListener(view -> {
            if (mediaPlayer == null) {
                initPlayer(item.getVoice(), tvRecord);
            } else {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer = null;
                } else {
                    initPlayer(item.getVoice(), tvRecord);
                }
            }
        });

        uploadAdapter = new UploadAdapter(getContext(), SHOWTYPE);
        rvUpload.setLayoutManager(new GridLayoutManager(getContext(), 4));
        if (!TextUtils.isEmpty(item.getImg())) {
            List<String> imgs = Arrays.asList(item.getImg().split(","));
            uploadAdapter.setData(imgs);
        } else {
            List<String> imgs = new ArrayList<>();
            uploadAdapter.setData(imgs);
        }
        uploadAdapter.setVideoUrl(item.getCoverUrl());
        uploadAdapter.setHaveAudio(true);
        rvUpload.setAdapter(uploadAdapter);
        uploadAdapter.setOnItemClickListener(new UploadAdapter.onItemClickListener() {
            @Override
            public void onAudioClick() {

            }

            @Override
            public void onVideoClick() {

            }

            @Override
            public void onShowVideoClick(String coverUrl) {
                //PopupWindowUtil.createVideoPop(activity, item.getVideo(), item.getCoverUrl()).showCenter(R.layout.fragment_complain_list);
                //PopupWindowUtil.createVideoPop(activity, item.getVideo(), item.getCoverUrl()).showCenter(R.layout.fragment_complain_list);
                ARouter.getInstance().build(ARouterUrlKt.VideoPlay)
                        .withString("videoUrl", item.getVideo())
                        .withString("coverUrl", item.getCoverUrl())
                        .withString("title", item.getContent())
                        .navigation(getContext());
            }

            @Override
            public void onDeleteVideoClick() {

            }

            @Override
            public void onAddClick() {

            }

            @Override
            public void onDelImgClick(int position) {

            }

            @Override
            public void onImgClick(List<String> imgUrls, int position) {
                PopupWindowUtil.createImageDialog(activity, imgUrls.get(position)).showCenter(R.layout.fragment_repairs_list);
            }
        });
    }

    //    播放录音
    private void initPlayer(String filePath, TextView textView) {
//        关闭上一个播放的录音
        if (recordTimer != null) {
            recordTimer.cancel();
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
        }
//        开始新的播放录音
        recordTimer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> textView.getBackground().setLevel(textView.getBackground().getLevel() == 2 ? 1 : 2));
            }
        };
        recordTimer.schedule(timerTask, 0, 500);
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnCompletionListener(mediaPlayer -> {
                if (recordTimer != null) {
                    recordTimer.cancel();
                }
            });
            try {
                mediaPlayer.setDataSource(activity, Uri.parse(filePath));
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                }
            } catch (IOException e) {
                mediaPlayer = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface OnFinishListener {
        void OnFinish(int pos);
    }

    public void setOnFinishListener(OnFinishListener onFinishListener) {
        this.onFinishListener = onFinishListener;
    }
}
